//
// Created by 崔世强 on 2018/3/10.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import UIKit

extension UIImage {
    private func resizableImage(name: String) -> UIImage {
        
        var normal = UIImage(named: name)!
        let imageWidth = normal.size.width * 0.5
        let imageHeight = normal.size.height * 0.5
        
        normal = resizableImage(withCapInsets: UIEdgeInsets(top: imageHeight, left: imageWidth, bottom: imageHeight, right: imageWidth), resizingMode: .stretch)
        
        return normal
    }
    
    /// 压缩图片到指定大小
    ///
    /// - Parameters:
    ///   - minSize: 图片允许的最小宽度（高度）
    ///   - maxSize: 图片允许的最大宽度（高度）
    ///   - maxLength: 压缩后最大字节大小
    /// - Returns: 压缩后图片的二进制数据
    func compressImage(minSize: CGFloat, maxSize: CGFloat,maxLength:Int) -> Data? {
        let newSize = self.scaleImage(minSize: minSize, maxSize: maxSize)
        print("压缩后的图片尺寸：\(newSize.width) * \(newSize.height)")
        let newImage = self.resizeImage(newSize: newSize)
        var compress: CGFloat = 0.05
        var data = newImage.jpegData(compressionQuality: compress)
        if data == nil {
            return nil
        }
        
        while data!.count > maxLength && compress > 0.01 {
            compress -= 0.02
            data = newImage.jpegData(compressionQuality: compress)
        }
        
        return data
    }
    
    /// 通过指定图片最大最小宽度(高度),等比缩放图片，如果图片不在指定的宽高比内，裁剪图片尺寸
    ///
    /// - Parameters:
    ///   - minSize: 图片允许的最小宽度（高度）
    ///   - maxSize: 图片允许的最大宽度（高度）
    /// - Returns: 获得图片的size
    func scaleImage(minSize: CGFloat, maxSize: CGFloat) -> CGSize {
        let origSize = self.size
        if (origSize.width >= minSize && origSize.height >= minSize) && (origSize.width <= maxSize && origSize.height <= maxSize) {
            return origSize
        }
        let widthHeightRatio = origSize.width/origSize.height  //计算宽高比
        if widthHeightRatio <= (maxSize/minSize) || widthHeightRatio >= (minSize/maxSize) {
            let ratio = max(origSize.width, origSize.height)/maxSize
            return CGSize(width: origSize.width/ratio, height: origSize.height/ratio)
        } else {
            let ratio = max(origSize.width, origSize.height)/minSize
            return CGSize(width: origSize.width/ratio, height: origSize.height/ratio)
        }
    }
    
    /// 获得指定size的图片
    ///
    /// - Parameter newSize: 指定的size
    /// - Returns: 调整后的图片
    func resizeImage(newSize: CGSize) -> UIImage {
        // Determine whether the screen is retina
        UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
        
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
}
